import { v4 as uuidv4 } from 'uuid';
import bcrypt from 'bcryptjs';

// 生成初始用户数据
const generateUsers = () => {
  const users = [
    {
      id: '1',
      username: 'admin',
      email: 'admin@example.com',
      name: '管理员',
      role: 'admin',
      avatar: 'https://avatars.githubusercontent.com/u/1?v=4',
      createdAt: new Date('2024-01-01'),
      lastLoginAt: new Date(),
      status: 'active'
    },
    {
      id: '2',
      username: 'user1',
      email: 'user1@example.com',
      name: '张三',
      role: 'user',
      avatar: 'https://avatars.githubusercontent.com/u/2?v=4',
      createdAt: new Date('2024-02-01'),
      lastLoginAt: new Date(Date.now() - 24 * 60 * 60 * 1000),
      status: 'active'
    },
    {
      id: '3',
      username: 'editor',
      email: 'editor@example.com',
      name: '李四',
      role: 'editor',
      avatar: 'https://avatars.githubusercontent.com/u/3?v=4',
      createdAt: new Date('2024-03-01'),
      lastLoginAt: new Date(Date.now() - 2 * 60 * 60 * 1000),
      status: 'active'
    }
  ];

  // 为用户添加加密密码 (密码统一为 123456)
  return users.map(user => ({
    ...user,
    password: bcrypt.hashSync('123456', 10)
  }));
};

// 生成初始文章数据
const generateArticles = () => {
  const categories = ['技术', '生活', '旅游', '美食', '读书', '电影'];
  const tags = ['React', 'Vue', 'JavaScript', 'TypeScript', 'Node.js', '微前端', '前端', '后端'];
  
  const articles = [];
  
  for (let i = 1; i <= 20; i++) {
    articles.push({
      id: i.toString(),
      title: `示例文章标题 ${i}`,
      content: `这是第${i}篇示例文章的内容。这里可以包含丰富的文本内容，包括段落、列表、代码片段等。\n\n## 子标题\n\n这是一个子标题下的内容。微前端架构为现代前端开发带来了新的可能性。\n\n### 技术要点\n\n1. 应用隔离\n2. 独立部署\n3. 技术栈自由\n4. 渐进升级\n\n\`\`\`javascript\n// 示例代码\nconst app = createApp({\n  name: 'MicroApp'\n});\n\`\`\`\n\n这篇文章展示了如何在实际项目中应用这些概念。`,
      summary: `这是第${i}篇文章的摘要，简要介绍了文章的主要内容和观点。`,
      category: categories[Math.floor(Math.random() * categories.length)],
      tags: tags.slice(0, Math.floor(Math.random() * 3) + 1),
      authorId: Math.floor(Math.random() * 3) + 1,
      status: Math.random() > 0.2 ? 'published' : 'draft',
      viewCount: Math.floor(Math.random() * 1000),
      likeCount: Math.floor(Math.random() * 50),
      commentCount: Math.floor(Math.random() * 20),
      createdAt: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000),
      updatedAt: new Date(Date.now() - Math.floor(Math.random() * 7) * 24 * 60 * 60 * 1000),
      publishedAt: Math.random() > 0.3 ? new Date(Date.now() - Math.floor(Math.random() * 20) * 24 * 60 * 60 * 1000) : null,
      coverImage: `https://picsum.photos/800/400?random=${i}`,
      featured: Math.random() > 0.8
    });
  }
  
  return articles;
};

// 生成消息数据
const generateMessages = () => {
  const messageTypes = ['info', 'warning', 'error', 'success'];
  const messages = [];
  
  for (let i = 1; i <= 10; i++) {
    messages.push({
      id: uuidv4(),
      type: messageTypes[Math.floor(Math.random() * messageTypes.length)],
      content: `来自${Math.random() > 0.5 ? 'React主应用' : 'Vue3子应用'}的测试消息 ${i}`,
      source: Math.random() > 0.5 ? 'react-main' : 'vue3-sub',
      target: Math.random() > 0.5 ? 'vue3-sub' : 'react-main',
      data: {
        timestamp: Date.now(),
        userId: Math.floor(Math.random() * 3) + 1,
        extra: `附加数据 ${i}`
      },
      createdAt: new Date(Date.now() - Math.floor(Math.random() * 60) * 60 * 1000),
      status: 'sent'
    });
  }
  
  return messages;
};

// 生成统计数据
const generateStats = () => {
  return {
    dashboard: {
      totalUsers: 156,
      totalArticles: 89,
      totalViews: 12543,
      totalMessages: 234,
      todayVisits: 45,
      weeklyGrowth: 12.5,
      monthlyRevenue: 8900,
      satisfaction: 4.7
    },
    charts: {
      userGrowth: Array.from({ length: 12 }, (_, i) => ({
        month: `2024-${String(i + 1).padStart(2, '0')}`,
        users: Math.floor(Math.random() * 50) + 20,
        articles: Math.floor(Math.random() * 30) + 10
      })),
      articleViews: Array.from({ length: 7 }, (_, i) => ({
        date: new Date(Date.now() - (6 - i) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        views: Math.floor(Math.random() * 500) + 100,
        unique: Math.floor(Math.random() * 300) + 50
      })),
      categoryDistribution: [
        { category: '技术', count: 45, percentage: 35 },
        { category: '生活', count: 32, percentage: 25 },
        { category: '旅游', count: 25, percentage: 20 },
        { category: '美食', count: 15, percentage: 12 },
        { category: '其他', count: 10, percentage: 8 }
      ]
    }
  };
};

// 创建数据存储
class DataStore {
  constructor() {
    this.users = generateUsers();
    this.articles = generateArticles();
    this.messages = generateMessages();
    this.stats = generateStats();
    this.sessions = new Map(); // 存储用户会话
  }

  // 用户相关方法
  getUsers() {
    return this.users.map(user => {
      const { password, ...userWithoutPassword } = user;
      return userWithoutPassword;
    });
  }

  getUserById(id) {
    const user = this.users.find(u => u.id === id);
    if (user) {
      const { password, ...userWithoutPassword } = user;
      return userWithoutPassword;
    }
    return null;
  }

  getUserByUsername(username) {
    return this.users.find(u => u.username === username);
  }

  getUserByEmail(email) {
    return this.users.find(u => u.email === email);
  }

  addUser(userData) {
    const newUser = {
      id: uuidv4(),
      ...userData,
      createdAt: new Date(),
      lastLoginAt: null,
      status: 'active'
    };
    this.users.push(newUser);
    const { password, ...userWithoutPassword } = newUser;
    return userWithoutPassword;
  }

  updateUser(id, userData) {
    const index = this.users.findIndex(u => u.id === id);
    if (index !== -1) {
      this.users[index] = { ...this.users[index], ...userData };
      const { password, ...userWithoutPassword } = this.users[index];
      return userWithoutPassword;
    }
    return null;
  }

  // 文章相关方法
  getArticles(filters = {}) {
    let filtered = [...this.articles];
    
    if (filters.category) {
      filtered = filtered.filter(a => a.category === filters.category);
    }
    
    if (filters.status) {
      filtered = filtered.filter(a => a.status === filters.status);
    }
    
    if (filters.authorId) {
      filtered = filtered.filter(a => a.authorId === filters.authorId);
    }
    
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase();
      filtered = filtered.filter(a => 
        a.title.toLowerCase().includes(keyword) ||
        a.content.toLowerCase().includes(keyword) ||
        a.tags.some(tag => tag.toLowerCase().includes(keyword))
      );
    }
    
    // 排序
    if (filters.sortBy) {
      filtered.sort((a, b) => {
        if (filters.sortBy === 'createdAt') {
          return new Date(b.createdAt) - new Date(a.createdAt);
        }
        if (filters.sortBy === 'viewCount') {
          return b.viewCount - a.viewCount;
        }
        if (filters.sortBy === 'likeCount') {
          return b.likeCount - a.likeCount;
        }
        return 0;
      });
    }
    
    return filtered;
  }

  getArticleById(id) {
    return this.articles.find(a => a.id === id);
  }

  addArticle(articleData) {
    const newArticle = {
      id: uuidv4(),
      ...articleData,
      viewCount: 0,
      likeCount: 0,
      commentCount: 0,
      createdAt: new Date(),
      updatedAt: new Date(),
      publishedAt: articleData.status === 'published' ? new Date() : null
    };
    this.articles.push(newArticle);
    return newArticle;
  }

  updateArticle(id, articleData) {
    const index = this.articles.findIndex(a => a.id === id);
    if (index !== -1) {
      this.articles[index] = { 
        ...this.articles[index], 
        ...articleData, 
        updatedAt: new Date() 
      };
      return this.articles[index];
    }
    return null;
  }

  deleteArticle(id) {
    const index = this.articles.findIndex(a => a.id === id);
    if (index !== -1) {
      return this.articles.splice(index, 1)[0];
    }
    return null;
  }

  // 消息相关方法
  getMessages(filters = {}) {
    let filtered = [...this.messages];
    
    if (filters.source) {
      filtered = filtered.filter(m => m.source === filters.source);
    }
    
    if (filters.type) {
      filtered = filtered.filter(m => m.type === filters.type);
    }
    
    return filtered.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  }

  addMessage(messageData) {
    const newMessage = {
      id: uuidv4(),
      ...messageData,
      createdAt: new Date(),
      status: 'sent'
    };
    this.messages.push(newMessage);
    return newMessage;
  }

  // 统计相关方法
  getStats() {
    return this.stats;
  }

  updateStats() {
    // 更新实时统计数据
    this.stats.dashboard.totalUsers = this.users.length;
    this.stats.dashboard.totalArticles = this.articles.length;
    this.stats.dashboard.totalMessages = this.messages.length;
    return this.stats;
  }

  // 会话管理
  addSession(userId, token) {
    this.sessions.set(token, {
      userId,
      createdAt: new Date(),
      lastAccess: new Date()
    });
  }

  getSession(token) {
    return this.sessions.get(token);
  }

  removeSession(token) {
    return this.sessions.delete(token);
  }

  clearExpiredSessions() {
    const now = new Date();
    for (const [token, session] of this.sessions.entries()) {
      // 24小时过期
      if (now - session.lastAccess > 24 * 60 * 60 * 1000) {
        this.sessions.delete(token);
      }
    }
  }
}

// 导出单例实例
export default new DataStore();